derived() Svelte store

Posted on 2023-02-12 by

henrikvilhelmberglund

Derived stores are a way to create stores from existing stores .

The derived store takes an existing store and a function to apply to the value.
10 * 2 = 20
<script>
	import { writable, derived } from "svelte/store";
	const num = writable(10);
	const newNum = derived(num, (haha) => {
		return haha * 2;
	});
</script>

<input bind:value={$num} type="number" />

<div>
	{$num} * 2 =
	{$newNum}
</div>

You can derive from one store or from many stores .

Here the store called multiplication is derived from two stores.
10 * 2 = 20
10 * 42 = 420
<script>
	import { writable, derived } from "svelte/store";
	const num = writable(10);
	const num2 = writable(42);

	// derived from one store
	const doubleOfNum = derived(num, (haha) => {
		return haha * 2;
	});

	const multiplication = derived([num, num2], ([$num, $num2]) => {
		return $num * $num2;
	});
</script>

<input bind:value={$num} type="number" />
<input bind:value={$num2} type="number" />

<div>
	{$num} * 2 =
	{$doubleOfNum}
</div>

<div>
	{$num} * {$num2} =
	{$multiplication}
</div>

You can also get the derived value synchronously or asynchronously .

When adding the second parameter 'set' the derived function is assumed to be asynchronous and the return statement doesn't do anything anymore.
10 * 2 = 20
10 * 42 = 420
delayed: undefined
<script>
	import { writable, derived } from "svelte/store";
	const num = writable(10);
	const num2 = writable(42);

	// derived from one store
	const doubleOfNum = derived(num, (haha) => {
		return haha * 2;
	});

	const multiplication = derived([num, num2], ([$num, $num2]) => {
		return $num * $num2;
	});
  
	const delayedNum = derived(num, ($num, set) => {
		return $num;
	});
</script>

<input bind:value={$num} type="number" />
<input bind:value={$num2} type="number" />

<div>
	{$num} * 2 =
	{$doubleOfNum}
</div>

<div>
	{$num} * {$num2} =
	{$multiplication}
</div>

<div>
	delayed: {$delayedNum}
</div>